package com.cytech.cloudclinic.dialog;

import android.app.AlertDialog;
import android.app.Dialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.cytech.cloudclinic.R;
import com.cytech.cloudclinic.adapter.AddDrugTagAdapter;
import com.cytech.cloudclinic.base.BaseBean;
import com.cytech.cloudclinic.base.BaseObserver;
import com.cytech.cloudclinic.bean.AddDrugTag;
import com.cytech.cloudclinic.bean.Drug;
import com.cytech.cloudclinic.bean.event.RefreshAction;
import com.cytech.cloudclinic.utils.ConvertUtils;
import com.cytech.cloudclinic.utils.RequestWithViewUtils;
import com.yechaoa.yutils.ToastUtil;
import com.yechaoa.yutils.YUtils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 修改药品默认信息对话框
 */
public class EditDrugDefaultDialog extends DialogFragment {
    @BindView(R.id.diglog_drug_count_rv)
    RecyclerView countRv;
    @BindView(R.id.diglog_drug_use_rv)
    RecyclerView useRv;
    @BindView(R.id.diglog_drug_dosage_rv)
    RecyclerView dosageRv;
    @BindView(R.id.diglog_drug_frequency_rv)
    RecyclerView frequencyRv;

    @BindView(R.id.tv_prescription_child_drug_weight)
    TextView countTv;
    @BindView(R.id.tv_prescription_child_drug_frequency)
    TextView frequencyTv;
    @BindView(R.id.tv_prescription_child_drug_use)
    TextView useTv;
    @BindView(R.id.tv_prescription_child_drug_dosage)
    TextView dosageTv;

    @BindView(R.id.tv_count_max)
    TextView countMax;
    @BindView(R.id.tv_count_min)
    TextView countMin;
    @BindView(R.id.tv_count_head_unit)
    TextView headCountUnitTv;
    @BindView(R.id.tv_frequency_head_unit)
    TextView headFrequencyUnitTv;
    @BindView(R.id.frequency_unit_max)
    TextView frequencyMax;
    @BindView(R.id.frequency_unit_min)
    TextView frequencyMin;
    @BindView(R.id.dialog_tv_drug_name)
    TextView drugName;

    private List<AddDrugTag> countList;
    private List<AddDrugTag> frequencyList;
    private List<AddDrugTag> useList;
    private List<AddDrugTag> dosageList;
    private AddDrugTagAdapter countAdapter;
    private AddDrugTagAdapter frequencyAdapter;
    private AddDrugTagAdapter useAdapter;
    private AddDrugTagAdapter dosageAdapter;

    private Drug drug;

    private OnSaveClickListener onSaveClickListener;


    public EditDrugDefaultDialog(int drug_tag_id, Drug drug,OnSaveClickListener onSaveClickListener) {
        this.onSaveClickListener = onSaveClickListener;
        Bundle bundle = new Bundle();
        bundle.putInt("drug_tag_id",drug_tag_id);
        bundle.putSerializable("drug",drug);
        setArguments(bundle);
    }

    @Override
    public void onStart() {
        super.onStart();
        WindowManager.LayoutParams lp = getDialog().getWindow().getAttributes();
        lp.width = (int) (0.9* YUtils.getScreenWidth());
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        getDialog().getWindow().setAttributes(lp);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        // Get the layout inflater
        LayoutInflater inflater = getActivity().getLayoutInflater();
        View view = inflater.inflate(R.layout.dialog_edit_drug_default_info, null);
        ButterKnife.bind(this, view);
        builder.setView(view);
        initCountRv();
        initUseRv();
        initDosageRv();
        initFrequencyRv();

        int drugParentTagId = getArguments().getInt("drug_tag_id");
        drug = (Drug) getArguments().getSerializable("drug");

        drugName.setText(drug.drug_name);
        countTv.setText(String.valueOf(drug.number));
        useTv.setText(drug.usage_mode);
        dosageTv.setText(drug.frequency);
        frequencyTv.setText(String.valueOf(drug.dosage));

        countMax.setText(drug.subunit);
        countMin.setText(drug.parent_unit);
        headCountUnitTv.setText(drug.subunit);
        frequencyMax.setText(drug.parent_unit);
        frequencyMin.setText(drug.subunit);
        headFrequencyUnitTv.setText(drug.subunit);


        getSummaryList(3,drugParentTagId);
        return builder.create();
    }

    //数量
    private void initCountRv() {
        countList = buildNumValue();
        countAdapter = new AddDrugTagAdapter(R.layout.item_add_drug_tag, countList);
        countRv.setLayoutManager(new GridLayoutManager(getActivity(), 3));
        countRv.setAdapter(countAdapter);

        countAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                String value = countAdapter.getItem(position).value;
                countTv.setText(ConvertUtils.getRealNumValue(value, countTv.getText().toString()));
            }
        });
    }

    //频次
    private void initFrequencyRv() {
        frequencyList = buildNumValue();
        frequencyAdapter = new AddDrugTagAdapter(R.layout.item_add_drug_tag, frequencyList);
        frequencyRv.setLayoutManager(new GridLayoutManager(getActivity(), 3));
        frequencyRv.setAdapter(frequencyAdapter);

        frequencyAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                String value = frequencyAdapter.getItem(position).value;
                frequencyTv.setText(ConvertUtils.getRealNumValue(value, frequencyTv.getText().toString()));
            }
        });
    }

    //用法
    private void initUseRv() {
        useList = new ArrayList<>();
        useAdapter = new AddDrugTagAdapter(R.layout.item_add_drug_tag, useList);
        useRv.setLayoutManager(new GridLayoutManager(getActivity(), 2));
        useRv.setAdapter(useAdapter);

        useAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                useAdapter.setCurrentPos(position);
                useTv.setText(useAdapter.getItem(position).value);
            }
        });
    }

    //用量
    private void initDosageRv() {
        dosageList = new ArrayList<>();
        dosageAdapter = new AddDrugTagAdapter(R.layout.item_add_drug_tag, dosageList);
        dosageRv.setLayoutManager(new GridLayoutManager(getActivity(), 3));
        dosageRv.setAdapter(dosageAdapter);

        dosageAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                dosageAdapter.setCurrentPos(position);
                dosageTv.setText(dosageAdapter.getItem(position).value);
            }
        });
    }

    @OnClick(R.id.dialog_update_unit_cancel)
    public void onClickCancel(View view){
        dismiss();
    }

    @OnClick(R.id.dialog_update_unit_save)
    public void onClickSave(View view){
        dismiss();
        if(onSaveClickListener!=null){
            drug.number = ConvertUtils.toInt(countTv.getText().toString());
            drug.usage_mode = useTv.getText().toString();
            drug.frequency = dosageTv.getText().toString();
            drug.dosage =  ConvertUtils.toInt(frequencyTv.getText().toString());
            onSaveClickListener.onSave(drug);
        }

    }



    public void getSummaryList(int mode,int drugParentId) {
        JSONObject json = new JSONObject();
        try {
            json.put("mode_id",mode);
            json.put("drug_id",drugParentId);

        } catch (JSONException e) {
            e.printStackTrace();
        }
        String requestStr = json.toString();
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestStr);
        RequestWithViewUtils.getInstance().addDisposable(RequestWithViewUtils.getInstance().apiServer.getSummaryList(body), new BaseObserver<BaseBean<List<AddDrugTag>>>(null, false) {
            @Override
            public void onSuccess(BaseBean<List<AddDrugTag>> o) {
               if(mode == 3){
                    useAdapter.setNewInstance(o.result);
                    useAdapter.notifyDataSetChanged();
                    getSummaryList(2,drugParentId);
               }else if(mode == 2){
                    dosageAdapter.setNewInstance(o.result);
               }
            }

            @Override
            public void onError(String msg) {

            }
        });
    }


    public List<AddDrugTag> buildNumValue(){
        List<AddDrugTag> numList = new ArrayList<>();
        numList.add(new AddDrugTag("1",false));
        numList.add(new AddDrugTag("2",false));
        numList.add(new AddDrugTag("3",false));
        numList.add(new AddDrugTag("4",false));
        numList.add(new AddDrugTag("5",false));
        numList.add(new AddDrugTag("6",false));
        numList.add(new AddDrugTag("7",false));
        numList.add(new AddDrugTag("8",false));
        numList.add(new AddDrugTag("9",false));
        numList.add(new AddDrugTag("0",false));
        numList.add(new AddDrugTag(".",false));
        numList.add(new AddDrugTag("清除",false));
        return numList;
    }

    public interface OnSaveClickListener{
        void onSave(Drug drug);
    }

}
